package com.changgou.order.service.impl;

import com.changgou.entity.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.service.CarService;
import com.changgou.order.pojo.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CarServiceImpl implements CarService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SpuFeign spuFeign;
    @Autowired
    private SkuFeign skuFeign;

    @Override
    public void add(Integer num, Long id, String username) {
        if (num < 0) {
            redisTemplate.boundHashOps("Cart_" + username).delete(id);
            Long size = redisTemplate.boundHashOps("Cart_" + username).size();
            if (size == null || size <= 0) {
                redisTemplate.delete("Cart_" + username);
            }
            return;
        }
        //查 询商品的详情
        //1)查询Sku
        Result<Sku> skuResult = skuFeign.findById(id);
        Sku sku = skuResult.getData();
        //2)查询Spu，
        Result<Spu> spuResult = spuFeign.findById(sku.getSpuId());
        Spu spu = spuResult.getData();
        //将加入购物车的商品信息封装成OrderItem
        OrderItem orderItem = CreateItem(num, id, sku, spu);
        redisTemplate.boundHashOps("Cart_" + username).put(id, orderItem);
    }

    @Override
    public List<OrderItem> list(String username) {
        //redisTemplate. boundHashOps ("Cart_ "+username). values() ;获取指定命名空间下所有数据
        return redisTemplate.boundHashOps("Cart_" + username).values();
    }

    private OrderItem CreateItem(Integer num, Long id, Sku sku, Spu spu) {
        OrderItem orderItem = new OrderItem();
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        orderItem.setSkuId(id.toString());
        orderItem.setSpuId(spu.getId().toString());
        orderItem.setName(sku.getName());
        orderItem.setPrice(sku.getPrice());
        orderItem.setNum(num);
        orderItem.setMoney(num * orderItem.getPrice());
        return orderItem;
    }
}
